package com.chixing.service.impl;

import com.chixing.mapper.OwnCouponMapper;
import com.chixing.mapper.SendCouponMapper;
import com.chixing.pojo.OwnCoupon;
import com.chixing.pojo.OwnCouponExample;
import com.chixing.pojo.SendCoupon;
import com.chixing.pojo.SendCouponExample;
import com.chixing.service.CouponService;
import com.chixing.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private SendCouponMapper sendCouponMapper;

    @Autowired
    private OwnCouponMapper ownCouponMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ServerResult getAll(Integer memberId) {
        SendCouponExample example = new SendCouponExample();
        example.createCriteria().andStatusEqualTo(0);
        List<SendCoupon> sendCouponList = sendCouponMapper.selectByExample(example);
        Date date = new Date();

        if (sendCouponList != null && sendCouponList.size() > 0) {
            for (int i = 0; i < sendCouponList.size(); i++) {

                if (sendCouponList.get(i).getSendCouponStarttime() != null) {
                    if (sendCouponList.get(i).getSendCouponStarttime().getTime() > date.getTime() && sendCouponList.get(i).getSendCouponEndtime().getTime() < date.getTime()) {
                        sendCouponList.remove(i);
                        System.out.println("=======1、sendCouponList======" + sendCouponList) ;
                        break;
                    }
                }


                //用户有该优惠券并且未使用
                OwnCouponExample ownCouponExample = new OwnCouponExample();
                if (sendCouponList.get(i).getSendCouponStarttime() != null) {
                    ownCouponExample.createCriteria().andMemberIdEqualTo(memberId).andCouponIdEqualTo(sendCouponList.get(i).getSendCouponId()).andOwnCouponTimeBetween(new Date(sendCouponList.get(i).getSendCouponStarttime().getTime()),
                            new Date(sendCouponList.get(i).getSendCouponEndtime().getTime()));
                } else {
                    ownCouponExample.createCriteria().andMemberIdEqualTo(memberId).andCouponIdEqualTo(sendCouponList.get(i).getSendCouponId()).andOwnCouponStatusEqualTo(0);
                }
                List<OwnCoupon> ownCouponList = ownCouponMapper.selectByExample(ownCouponExample);

                if (ownCouponList.size() > 0 && ownCouponList != null) {
                    sendCouponList.remove(i);
                    System.out.println("=======2、sendCouponList======" + sendCouponList) ;
                    break;
                }


//                for (int j = 0; j < ownCouponList.size(); j++) {
//                    if (ownCouponList.get(i).getOwnCouponTime().getTime() >= sendCouponList.get(i).getSendCouponStarttime().getTime() && ownCouponList.get(i).getOwnCouponTime().getTime() <= sendCouponList.get(i).getSendCouponEndtime().getTime()) {
//                        sendCouponList.remove(i);
//                    }
//                }

            }

            if (sendCouponList != null && sendCouponList.size() > 0)
                return ServerResult.getSussess(sendCouponList);
        }

        return ServerResult.getFail("您暂时没有优惠券可领！请稍后再来，谢谢！");
    }

    @Override
    public ServerResult receiveCoupon(Integer couponId, Integer memberId) {

        SendCoupon sendCoupon = sendCouponMapper.selectByPrimaryKey(couponId);

        OwnCoupon ownCoupon = new OwnCoupon();
        ownCoupon.setCouponId(couponId);
        ownCoupon.setCouponNo(UUID.randomUUID().toString().replace("-", ""));
        ownCoupon.setMemberId(memberId);
        ownCoupon.setOwnCouponTime(new Date());
        if (sendCoupon.getSendCouponStarttime() == null && sendCoupon.getSendCouponEndtime() == null) {
            ownCoupon.setCouponStarttime(new Date());
            ownCoupon.setCouponEndtime(new Date(new Date().getTime() + sendCoupon.getSendCouponPeriod() * 24 * 60 * 60 * 1000));
        } else {
            ownCoupon.setCouponStarttime(sendCoupon.getSendCouponStarttime());
            ownCoupon.setCouponEndtime(sendCoupon.getSendCouponEndtime());
        }
        ownCoupon.setOwnCouponStatus(0);
        ownCoupon.setOwnCouponPrice(sendCoupon.getSendCouponPrice());
        ownCoupon.setOwnCouponValidprice(sendCoupon.getSendCouponValidprice());

        int rows = ownCouponMapper.insert(ownCoupon);
//        System.out.println("领好优惠券后的我的优惠券id：" + ownCoupon.getOwnCouponId());

//        加入redis的db1中，并设置过期时间测试为1分钟
//        LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
//        lettuceConnectionFactory.setDatabase(1);
//        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
//        lettuceConnectionFactory.resetConnection();
        redisTemplate.opsForSet().add(String.valueOf(ownCoupon.getOwnCouponId()),ownCoupon);
//        sendCoupon.getSendCouponPeriod()
        redisTemplate.expire(String.valueOf(ownCoupon.getOwnCouponId()),sendCoupon.getSendCouponPeriod(),TimeUnit.DAYS);


        if (rows == 1) {
            return ServerResult.saveSussess("已领取");
        }

        return ServerResult.saveFail("领取失败");
    }

    @Override
    public ServerResult getUserCoupon(Integer memberId) {
        OwnCouponExample example = new OwnCouponExample();
        example.createCriteria().andMemberIdEqualTo(memberId);
        List<OwnCoupon> ownCouponList = ownCouponMapper.selectByExample(example);

        if (ownCouponList.size() > 0 && ownCouponList != null) {
            return ServerResult.getSussess(ownCouponList);
        }

        return ServerResult.getFail("点击领取优惠券");
    }

    @Override
    public OwnCoupon getById(Integer couponId) {
        OwnCoupon ownCoupon = ownCouponMapper.selectByPrimaryKey(couponId);

        if (ownCoupon != null)
            return ownCoupon;
        return null;
    }

    @Override
    public int updateById(Integer couponId) {
        System.out.println("优惠券已使用或优惠券已失效");
        OwnCoupon ownCoupon = new OwnCoupon();
        ownCoupon.setOwnCouponId(couponId);
        ownCoupon.setOwnCouponStatus(1);
        int rows = ownCouponMapper.updateByPrimaryKeySelective(ownCoupon);

        return rows;
    }

    @Override
    public int updateById2Lapse(Integer coupnId) {
        System.out.println("优惠券已使用或优惠券已失效");
        OwnCoupon ownCoupon = new OwnCoupon();
        ownCoupon.setOwnCouponId(coupnId);
        ownCoupon.setOwnCouponStatus(2);
        int rows = ownCouponMapper.updateByPrimaryKeySelective(ownCoupon);
        return rows;
    }
}
